<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\common\constant\Constant;
use app\common\model\Coupon;
use app\common\model\UserCoupon;
use think\Db;
use think\Exception;

class CouponManager extends BaseManager
{

    /**
     * 获取用户的优惠券列表
     * @param int|null $type
     * @param int|null $detail
     * @param int $page
     * @param int $step
     * @return array
     */
    public static function CouponList(int $type=null,int $detail=null,int $page=1,int $step=Constant::PAGE_LIMIT):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if ($page < 1)
            $page = 1;
        try {   //获取优惠券列表
            $start = ($page - 1) * $step;
            $couponModel = new \app\common\model\Coupon();
            $count = $couponModel->where('shelves',Coupon::SHELVES_YES)
                ->where(function ($query) use($type){
                    if ($type){
                        $query->where('type',$type);
                    }
                })
                ->where(function ($query) use($detail){
                    if ($detail){
                        $query->where('detail',$detail);
                    }
                })
                ->count();

            $info = $couponModel->where('shelves',Coupon::SHELVES_YES)
                ->where(function ($query) use($type){
                    if ($type){
                        $query->where('type',$type);
                    }
                })
                ->where(function ($query) use($detail){
                    if ($detail){
                        $query->where('detail',$detail);
                    }
                })
                ->field('id,title,amount,type,detail,limit_amount,image,rate,validity,total,received,description,create_time,update_time')->limit($start,$step)->order('id desc')->select();
            if ($info){
                foreach ($info as $key => $value) {
                    $info[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
                    $info[$key]['update_time'] = date('Y-m-d H:i:s', $value['update_time']);  //格式化时间
                    if (strrpos($value['image'],'https')===false){
                        $info[$key]['image'] = cdnurl($value['image']);
                    }
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $info;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 领取优惠券
     * @param int $userId
     * @param int $couponId
     * @param int $system 0:用户领取 1:后台发放
     * @param bool $trans
     * @return array
     */
    public static function receiveCoupon(int $userId,int $couponId,int $system=Coupon::SYSTEM_NO,bool $trans=true):array
    {
        if($trans){
            Db::startTrans();
        }
        try {
            $couponModel = new \app\common\model\Coupon();
            $couponInfo = $couponModel->where('id',$couponId)->where('shelves',Coupon::SHELVES_YES)->find();
            if (!$couponInfo){
                throw new Exception('优惠券不存在');
            }
            if ($couponInfo['total'] <= $couponInfo['received']){
                throw new Exception('优惠券已领完');
            }
            $userCouponModel = new \app\common\model\UserCoupon();
            $userCouponInfo = $userCouponModel->where('user_id',$userId)->where('coupon_id',$couponId)->count();
            if ($system == Coupon::SYSTEM_NO){
                if ($userCouponInfo){
                    throw new Exception('您已领取过该优惠券');
                }
            }
            if ($system == Coupon::SYSTEM_NO) {
                $where = ['id' => $couponId, 'total' => Db::raw(' total > received '), 'shelves' => Coupon::SHELVES_YES];
                if (!Coupon::where($where)->update(['received' => Db::raw('received+1'), 'update_time' => time()])) {
                    throw new Exception('领取失败');
                }
            }
            $userCouponCreate = $userCouponModel->create([
                'user_id' => $userId,
                'coupon_id' => $couponId,
                'type' => $couponInfo['type'],
                'detail' => $couponInfo['detail'],
                'amount' => $couponInfo['amount'],
                'limit_amount' => $couponInfo['limit_amount'],
                'rate' => $couponInfo['rate'],
                'expires_time' => time() + ($couponInfo['validity'] * 3600 * 24),
                'received_time' => time(),
                'create_time' => time(),
                'donation' => $system,
                'update_time' => time()
            ]);
            if(!$userCouponCreate){
                throw new Exception('领取失败');
            }
            if ($trans){
                Db::commit();
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }

    /**
     * 获取用户的优惠券列表
     * @param int $userId
     * @param  $status
     * @param  $type
     * @param  $detail
     * @param int $page
     * @param int $step
     * @return array
     */
    public static function UserCouponList(int $userId, $status=null, $type=null, $detail=null, int $page=1,int $step=Constant::PAGE_LIMIT): array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if ($page < 1)
            $page = 1;
        try {
            $start = ($page - 1) * $step;
            $userCouponModel = new \app\common\model\UserCoupon();
            $count = $userCouponModel->where('user_id',$userId)
                ->where(function ($query) use($status){
                    if ($status==UserCoupon::STATUS_USED){
                        $query->where('status',UserCoupon::STATUS_USED);
                    }else if ($status==UserCoupon::STATUS_UNUSED){
                        $query->where('status',UserCoupon::STATUS_UNUSED);
                    }else if ($status==UserCoupon::STATUS_EXPIRED){
                        $query->where('expires_time','<',time());
                    }
                })
                ->where(function ($query) use($type){
                    if ($type){
                        $query->where('type',$type);
                    }
                })
                ->where(function ($query) use($detail){

                    if ($detail){
                        if (is_string($detail)){
                            $query->where('detail','in',$detail);
                        }else{
                            $query->where('detail',$detail);
                        }

                    }
                })
                ->count();

            $info = $userCouponModel->where('user_id',$userId)
                ->where(function ($query) use($status){
                    if ($status==UserCoupon::STATUS_USED){
                        $query->where('status',UserCoupon::STATUS_USED);
                    }else if ($status==UserCoupon::STATUS_UNUSED){
                        $query->where('status',UserCoupon::STATUS_UNUSED);
                    }else if ($status==UserCoupon::STATUS_EXPIRED){
                        $query->where('expires_time','<',time());
                    }
                })
                ->where(function ($query) use($type){
                    if ($type){
                        $query->where('type',$type);
                    }
                })
                ->where(function ($query) use($detail){
                    if ($detail){
                        if (is_string($detail)){
                            $query->where('detail','in',$detail);
                        }else{
                            $query->where('detail',$detail);
                        }

                    }
                })
                ->field('id,coupon_id,type,detail,amount,limit_amount,rate,expires_time,received_time,donation,status,create_time,update_time')->limit($start,$step)->select();
            if ($info) {
                foreach ($info as $key => $value) {
                    $info[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
                    $info[$key]['update_time'] = date('Y-m-d H:i:s', $value['update_time']);  //格式化时间
                    $info[$key]['expires_time'] = date('Y-m-d H:i:s', $value['expires_time']);  //格式化时间
                    $info[$key]['received_time'] = date('Y-m-d H:i:s', $value['received_time']);  //格式化时间
                    $couponInfo = Coupon::where('id',$value['coupon_id'])->field('title,image,description')->find();
                    if ($couponInfo){
                        $info[$key]['title'] = $couponInfo['title'];
                        $info[$key]['image'] = $couponInfo['image'];
                        $info[$key]['description'] = $couponInfo['description'];
                        if (strrpos($info[$key]['image'],'https')===false){
                            $info[$key]['image'] = cdnurl($info[$key]['image']);
                        }
                    }else{
                        $info[$key]['title'] = '';
                        $info[$key]['image'] = '';
                        $info[$key]['description'] = '';
                    }
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $info;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


}